<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实时时间转换指令</title>
  <script src="js/vue.js"></script>
</head>
<body>
  <div id="app">
    <div v-time="timeNow"></div>
    <div v-time="timeBefore"></div>
  </div>
  <script>
    Vue.directive('time', {
      bind: function(el, binding) {
        el.innerHTML = Time.getFormatTime(binding.value);
        el.__timeout = setInterval(() => {
          el.innerHTML = Time.getFormatTime(binding.value);
        }, 60000)
      },
      unbind: function() {
        clearInterval(el.__timeout);
        delete el.__timeout;
      }
    })
    //工具时间函数
    var Time = {
      //获取当前时间戳
      getUnix: function() {
        var date = new Date();
        return date.getTime();
      },
      //获取今天0点0分0秒的时间戳
      getTodayUnix: function() {
        var date = new Date();
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        return date.getTime();
      },
      //获取今年1月1日0点0分0秒的时间戳
      getYearUnix: function() {
        var date = new Date();
        date.setMonth(0);
        date.setDate(1);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        return date.getTime();
      },
      //获取标准年月日
      getLastDate: function(time) {
        var date = new Date(time);
        var month = this.parTime(date.getMonth() + 1);
        var day = this.parTime(date.getDate());
        return date.getFullYear() + '-' + month + "-" + day;
      },
      //小于10 添加个0
      parTime: function(value){
        return value < 10 ? '0' + value : value;
      },
      //转换时间
      getFormatTime: function(timestamp) {
        var now = this.getUnix();  //得到当前时间戳
        var today = this.getTodayUnix(); //今天0点时间戳
        var year = this.getYearUnix(); //今年0点时间戳

        var timer = (now - timestamp) / 1000; //转换为秒级时间戳
        var tip = '';

        if(timer <= 0) {
          tip = '刚刚';
        } else if(Math.floor(timer / 60) <= 0) {
          tip = '刚刚';
        } else if(timer < 3600) {
          tip = Math.floor(timer/60) + '分钟前';
        } else if(timer >= 3600 && (timestamp - today >= 0)) {
          tip = Math.floor(timer/3600) + '小时前';
        } else if (timer/86400 <= 31) {
          tip = Math.ceil(timer/86400) + '天前';
        } else {
          tip = this.getLastDate(timestamp);
        }
        return tip;
      }
    }
    var app = new Vue({
      el: "#app",
      data: {
        //是目前的最新时间
        timeNow: (new Date()).getTime(),
        //是一个写死的假定时间
        timeBefore: 1588930695721
      }
    })
  </script>
</body>
</html>